<template>
	<view class="container" v-show="pageLoaded">
		<swiper class="detail-banner-swiper">
			<swiper-item v-for="img of info.imgDetails" :key="img.attaId">
				<image class="banner-item" :src="img_baseUrl + img.url" mode="aspectFill" />
			</swiper-item>
		</swiper>
		<view class="detail-head">
			<view class="detail-price">¥{{ info.toShowPrice }}</view>
			<view class="detail-title">{{ info.name }}</view>
		</view>
		<view class="detail-attrs">
			<view v-if="stockNum > 0" class="detail-attr" @click="openPopup">
				<view class="detail-attr_name">选择</view>
				<view class="detail-attr_content">
					{{ specs + (specs ? "，" : "") + number + "件" }}
				</view>
				<view class="detail-attr_btn">
					<image :src="`${img_baseUrl}/statics/std/static/go_gray.png`" mode="aspectFill" />
				</view>
			</view>
			<view class="detail-attr">
				<view class="detail-attr_name">服务</view>
				<view class="detail-attr_content">
					支持快递（邮费0-22元） · 支持自提
				</view>
			</view>
		</view>
		<view class="detail-wrap_title">
			<!-- <image class="detail-wrap_title-bg" :src="`${img_baseUrl}/statics/std/static/my_icon7.png`"
				mode="aspectFill" /> -->
			<text class="detail-wrap_title-text">商品详情</text>
		</view>
		<view class="detail-content">
			<mp-html :content="info.goodsDesc" style="font-size: 28rpx; color: #4d4d4d; line-height: 48rpx; font-weight: 400;"/>
		</view>
		<view class="detail-footer">
			<view class="detail-footer-item" @click="toShop">
				<view class="detail-footer-img">
					<image :src="`${img_baseUrl}/statics/std/static/new/shop.png`" mode="aspectFill" />
				</view>
				<view>商家</view>
			</view>
			<view class="detail-footer-item" @click="goPage">
				<view class="detail-footer-img">
					<image :src="`${img_baseUrl}/statics/std/static/new/shopping_cart.png`" mode="aspectFill" />
					<!--<text class="detail-footer-num">99</text>-->
				</view>
				<view>购物车</view>
			</view>
			<view class="detail-footer-btns">
				<view v-if="stockNum > 0" class="detail-footer-btn1" @click="openPopup">
				  加入购物车
				</view>
				<view class="detail-footer-btn2" @click="buyNow">
				  {{ stockNum > 0 ? "立即购买" : "已售空" }}
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" :backgroundColor="'#ffffff'" :transStyle="{
        borderTopLeftRadius: '40rpx',
        borderTopRightRadius: '40rpx',
        overflow: 'hidden',
      }">
			<view class="popup-content">
				<image class="popup-close" :src="`${img_baseUrl}/statics/std/static/delete2.png`"
					@click="closePopup"></image>
				<view class="popup-head">
					<image class="popup-head-img" :src="img_baseUrl + info.imgAbbrev" mode="aspectFill" />
					<view class="popup-head-price">¥{{ price }}</view>
				</view>
				<scroll-view class="attr-details" :scroll-y="true" :enhanced="true" :show-scrollbar="false">
          <view
            v-for="(goodsSpecs, keyName) of info.goodsSpecs"
            :key="keyName"
            class="attr-detail"
          >
            <view class="attr-detail-title">{{ keyName }}</view>
            <view class="attr-detail-list">
              <view
                v-for="spec of goodsSpecs"
                :key="spec"
                :class="{
                  active: SpecIsActive(keyName, spec),
                  disabled: SpecIsDisabled(keyName, spec),
                }"
                class="attr-detail-item"
                @click="chooseSpecs(keyName, spec)"
              >
                <view class="attr-detail-item-content">{{ spec }}</view>
              </view>
            </view>
          </view>
					<view class="attr-detail row">
						<view class="attr-detail-title">数量</view>
						<number-box class="attr-detail-number-box" v-model="number" :max="stockNum" />
					</view>
				</scroll-view>
				<view class="attr-footer">
					<view class="attr-footer-btns">
						<view class="attr-footer-btn1" @click="inCart">加入购物车</view>
						<view class="attr-footer-btn2" @click="buyNow">立即购买</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
	import uniPopup from "../../components/uni-popup/uni-popup.vue";
	import numberBox from "../../components/number-box.vue";
	import requestPost, {
		requestGet
	} from "../../utils/request";

	const img_api = process.env.VUE_APP_BASEURL_IMG_API;

	export default {
		components: {
			mpHtml,
			uniPopup,
			numberBox,
		},
		props: {
			id: String,
		},
		data() {
			return {
				pageLoaded: false,
				loading: 2, // 0:不再加载; 1:加载中; 2:加载完成;
				info: {},
				img_baseUrl: img_api,
				number: 1,
        activeSpecs: []
			};
		},
		computed: {
			specs() {
			  return this.activeSpecs.join("，");
			},
			activeSku() {
			  return this.filterSkus(this.info.goodsSkus, this.activeSpecs)[0] || {};
			},
			price() {
			  return this.activeSku.price ? this.activeSku.price.toFixed(2) : this.info.price?.toFixed(2);
			},
			stockNum() {
			  // return this.activeSku.stockNum ? this.activeSku.stockNum : this.info.stockTotal;
        return (this.info.goodsSkus && this.info.goodsSkus.length > 0) ? (this.activeSku.stockNum ? this.activeSku.stockNum : 0) : this.info.stockTotal
			},
		},
		onShow() {
			this.loadDetail().then(() => {
				this.pageLoaded = true;
			});
		},
		methods: {
      goPage(){
        if (!wx.getStorageSync("X-Token")) {
        	uni.showModal({
        		title: '提示',
        		content: '您还没有登录，请前往登录',
        		showCancel: true,
        		success: function(res) {
        			if (res.confirm) {
        				uni.navigateTo({
        					url: '/pages/login/index'
        				});
        			} else if (res.cancel) {
        				console.log('用户点击取消');
        			}
        		}
        	});
        	return
        }
        this.toPage("/page_mall/cart/index");
      },
			toPage(url, params = {}) {
				let paramsString = "";
				for (const paramsKey in params) {
					if (!paramsString) {
						paramsString += "?";
					} else {
						paramsString += "&";
					}
					paramsString += `${paramsKey}=${params[paramsKey]}`;
				}
				uni.navigateTo({
					url: `${url}${paramsString}`,
				});
			},
			toShop() {
				const pages = getCurrentPages();
				if (
					pages.length >= 2 &&
					pages[pages.length - 2].route !== "page_mall/shop/shop"
				) {
					this.toPage("/page_mall/shop/shop", {
						id: this.info.storeId
					});
				} else {
					uni.navigateBack({
						delta: 1,
					});
				}
			},
			loadDetail() {
				return requestGet(`/shop/mobile/goods/${this.id}`).then(
					({
						code,
						data: info
					}) => {
						if (code !== 200) {
							info = {};
						}
						info.toShowPrice = info.price.toFixed(2);
            info.goodsDesc = info && info.goodsDesc ? info.goodsDesc.split("\t").join("&nbsp;&nbsp;&nbsp;&nbsp;") : '';
            info.goodsSkus.forEach((sku) => {
              sku.goodsSpec = JSON.parse(sku.goodsSpec);
            });
            if (info.goodsSpecs) {
              info.goodsSpecsKeys = Object.keys(info.goodsSpecs);
              const activeSpecs = Object.values(info.goodsSpecs).reduce(
                (acc, specs = []) => {
                  const activeSpec = specs.find((spec) => {
                    return this.filterSkus(acc.skus, [...acc._activeSpecs, spec])
                      .length;
                  });
                  if (activeSpec) {
                    const _activeSpecs = [...acc._activeSpecs, activeSpec];
                    return {
                      _activeSpecs: _activeSpecs,
                      skus: this.filterSkus(acc.skus, _activeSpecs),
                    };
                  } else {
                    // 都没有库存
                    return {
                      _activeSpecs: [],
                      skus: acc.skus,
                    };
                  }
                },
                { _activeSpecs: [], skus: info.goodsSkus }
              );
              console.log("初始规格组", activeSpecs._activeSpecs);
              this.activeSpecs = activeSpecs._activeSpecs;
            }
						this.info = info;
						this.loading = 0;
					}
				);
			},
			filterSkus(skus = [], specs = []) {
			  return specs.reduce((_skus, spec) => {
			    return _skus.filter((sku) => {
			      return sku.stockNum > 0 && sku.goodsSpec.includes(spec);
			    });
			  }, skus);
			},
      chooseSpecs(goodsSpecKey, spec) {
        if (this.SpecIsDisabled(goodsSpecKey, spec)) {
          return;
        }
        const keyIndex = this.info.goodsSpecsKeys.findIndex((goodsSpecsKey) => {
          return goodsSpecsKey === goodsSpecKey;
        });
        this.activeSpecs.splice(keyIndex, 1, spec);
      },
      SpecIsActive(goodsSpecKey, spec) {
        const keyIndex = this.info.goodsSpecsKeys.findIndex((goodsSpecsKey) => {
          return goodsSpecsKey === goodsSpecKey;
        });
        return this.activeSpecs[keyIndex] === spec;
      },
      SpecIsDisabled(goodsSpecKey, spec) {
        const keyIndex = this.info.goodsSpecsKeys.findIndex((goodsSpecsKey) => {
          return goodsSpecsKey === goodsSpecKey;
        });
        const _testSpecs = this.activeSpecs.toSpliced(keyIndex, 1, spec);
        return !this.filterSkus(this.info.goodsSkus, _testSpecs).length;
      },
			goodsInfo() {
				return {
					storeId: this.info.storeId, // 店铺id
					storeName: this.info.shopStore ? this.info.shopStore.name : "", // 店铺名称
					goodsId: Number(this.id), // 商品id
					goodsNum: this.number, // 商品数量
					name: this.info.name, // 商品名称
					imgAbbrev: this.info.imgAbbrev, // 商品缩略图
					price: Number(this.price), // 商品价格
					goodsSpec: this.specs, // 规格
          skuId: this.activeSku.skuId || null
				};
			},
			inCart() {
        if (!wx.getStorageSync("X-Token")) {
        	this.toPage("/pages/login/index");
        	return Promise.reject({
        		msg: "需要登录身份",
        	});
        }
				return requestPost("/shop/mobile/cart", this.goodsInfo()).then(
					({
						code
					}) => {
						if (code === 200) {
              this.$refs.popup.close();
							uni.showToast({
								title: "添加成功",
								icon: "success",
							});
						}
					}
				);
			},
			buyNow() {
        if (this.stockNum === 0) {
          return;
        }
				if (!wx.getStorageSync("X-Token")) {
					this.toPage("/pages/login/index");
					return Promise.reject({
						msg: "需要登录身份",
					});
				}
				this.$store.commit("setSettlementGoods", [this.goodsInfo()]);
				console.log(this.$store.state.settlementGoods);
				this.toPage("/page_mall/settle/index");
			},
			openPopup() {
				this.$refs.popup.open();
			},
			closePopup() {
				this.$refs.popup.close();
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: env(safe-area-inset-bottom);
	}

	swiper.detail-banner-swiper {
		height: 750rpx;

		&::v-deep {
			.wx-swiper-dots {
				width: 100%;
				height: 120rpx;
				background: linear-gradient(180deg,
						rgba(0, 0, 0, 0) 0%,
						rgba(0, 0, 0, 0.16) 100%);
				padding-top: 52rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				bottom: 0;
			}

			.wx-swiper-dot {
				width: 20rpx;
				height: 4rpx;
				margin: 0 6rpx;
				background: rgba(255, 255, 255, 0.6);
				border-radius: 10rpx;
				opacity: 1;

				&.wx-swiper-dot-active {
					background: #ffffff;
					opacity: 1;
				}
			}
		}
	}

	.banner-item {
		width: 100%;
		height: 100%;
		display: block;
	}

	.detail-head {
		padding: 32rpx 32rpx 0;

		.detail-price {
			font-family: 'D-DIN-Bold';
			font-size: 48rpx;
			font-weight: 700;
			color: #ff7614;
			line-height: 52rpx;
			margin-bottom: 24rpx;
		}

		.detail-title {
			font-size: 32rpx;
			font-weight: 700;
			color: rgba(0, 0, 0, 0.9);
			line-height: 44rpx;
		}
	}

	.detail-attrs {
		background: #f7f9fa;
		border-radius: 24rpx;
		padding: 0 24rpx;
		margin: 40rpx 32rpx 0;

		.detail-attr {
			display: flex;
			align-items: center;
			padding: 32rpx 0;

			.detail-attr_name {
				flex: none;
				font-size: 28rpx;
				font-weight: 400;
				color: #5f6f86;
				line-height: 44rpx;
				margin-right: 48rpx;
			}

			.detail-attr_content {
				flex: auto;
				font-size: 28rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.8);
				line-height: 44rpx;
			}

			.detail-attr_btn {
				flex: none;
				width: 32rpx;
				height: 32rpx;

				image {
					display: block;
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.detail-wrap_title {
		height: 72rpx;
		// border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
		padding: 0 32rpx;
		position: relative;
		display: flex;
		align-items: center;
		margin-top: 40rpx;

		// .detail-wrap_title-bg {
		// 	display: block;
		// 	width: 124rpx;
		// 	height: 84rpx;
		// 	position: absolute;
		// 	left: 0rpx;
		// 	top: -14rpx;
		// }

		.detail-wrap_title-text {
			font-size: 32rpx;
			font-weight: 700;
			color: rgba(0, 0, 0, 0.8);
			line-height: 44rpx;
			position: relative;
		}
	}

	.detail-content {
		padding: 26rpx 32rpx 150rpx;
	}

	.detail-footer {
		background: #ffffff;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 124rpx;
		border-top: 2rpx solid rgba(0, 0, 0, 0.1);
		padding-bottom: env(safe-area-inset-bottom);
		display: flex;
		align-items: center;

		.detail-footer-item {
			padding-bottom: 2rpx;
			display: flex;
			flex-flow: column nowrap;
			align-items: center;
			font-size: 24rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.5);
			line-height: 34rpx;
			min-width: 72rpx;
			margin-left: 40rpx;

			&:first-of-type {
				margin-left: 32rpx;
			}

			.detail-footer-img {
				width: 40rpx;
				height: 40rpx;
				position: relative;
				margin-bottom: 4rpx;

				image {
					display: block;
					width: 100%;
					height: 100%;
				}

				.detail-footer-num {
					width: 26rpx;
					height: 26rpx;
					background: #ffffff;
					box-shadow: 0 0 0 2rpx #eeeeee;
					border-radius: 26rpx;
					font-size: 20rpx;
					font-weight: 700;
					color: #2187ff;
					line-height: 26rpx;
					text-align: center;
					position: absolute;
					top: -6rpx;
					right: -8rpx;
				}
			}
		}

		.detail-footer-btns {
			display: flex;
			font-size: 28rpx;
			line-height: 40rpx;
			border-radius: 88rpx;
			overflow: hidden;
			margin-left: auto;
			margin-right: 32rpx;

			.detail-footer-btn1 {
				width: 220rpx;
				height: 88rpx;
				background: rgba(63,170,115,0.1);
				font-weight: 500;
				color: #3FAA73;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.detail-footer-btn2 {
				width: 220rpx;
				height: 88rpx;
				background: #3FAA73;
				font-weight: 700;
				color: #ffffff;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}

	.popup-content {
		max-height: 80vh;
		padding: 32rpx 32rpx 0;
		position: relative;

		.popup-close {
			width: 48rpx;
			height: 48rpx;
			position: absolute;
			right: 24rpx;
			top: 24rpx;
		}

		.popup-head {
			display: flex;
			align-items: flex-end;

			.popup-head-img {
				width: 96rpx;
				height: 96rpx;
				border-radius: 16rpx;
				margin-right: 24rpx;
			}

			.popup-head-price {
				font-size: 48rpx;
				font-weight: 700;
				color: #ff7614;
				line-height: 52rpx;
			}
		}

		.attr-details {
			max-height: calc(80vh - 128rpx - 48rpx - 124rpx - env(safe-area-inset-bottom));
			padding: 20rpx 0;

			.attr-detail {
				display: flex;
				flex-flow: column nowrap;

				&.row {
					flex-flow: row nowrap;
				}

				.attr-detail-title {
					font-size: 32rpx;
					font-weight: 700;
					color: #3d3d3d;
					line-height: 44rpx;
					margin-top: 28rpx;
				}

				.attr-detail-number-box {
					margin-top: 28rpx;
					margin-left: auto;
				}

				.attr-detail-list {
					font-size: 28rpx;
					font-weight: 400;
					color: rgba(0, 0, 0, 0.7);
					line-height: 40rpx;
					display: flex;
					flex-flow: row wrap;
					margin: 0 -8rpx 20rpx;

					.attr-detail-item {
						flex: 0 0 33.33333%;

						.attr-detail-item-content {
							height: 64rpx;
							background: #F3F6F5;
							border-radius: 8rpx;
							margin: 16rpx 8rpx 0;
							display: flex;
							justify-content: center;
							align-items: center;
							box-sizing: border-box;
						}

						&.active {
							.attr-detail-item-content {
								background: #3FAA73;
								color: #fff;
								// border: 2rpx solid #2187ff;
							}
						}
            &.disabled {
              .attr-detail-item-content {
                background: #faf9f8;
                color: rgba(0, 0, 0, 0.3);
              }
            }
					}
				}
			}
		}

		.attr-footer {
			width: 100vw;
			margin-left: -32rpx;
			margin-top: 40rpx;
			height: 124rpx;
			border-top: 2rpx solid rgba(0, 0, 0, 0.1);
			box-sizing: border-box;
			padding-left: 32rpx;
			display: flex;
			align-items: center;

			.attr-footer-btns {
				display: flex;
				font-size: 28rpx;
				line-height: 40rpx;
				border-radius: 88rpx;
				overflow: hidden;

				.attr-footer-btn1 {
					width: 343rpx;
					height: 88rpx;
					background: rgba(63,170,115,0.1);
					font-weight: 500;
					color: #3FAA73;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.attr-footer-btn2 {
					width: 343rpx;
					height: 88rpx;
					background: #3FAA73;
					font-weight: 700;
					color: #ffffff;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}
</style>